<template>
  <Card style="height:900px">
    <Form ref="groupForm" :model="groupForm" :rules="validRules" :label-width="90" inline>
        <FormItem label="工作组名称:" prop="groupName">
            <Input v-model="groupForm.groupName" placeholder="" :disabled="deleteFlag==='1'|| !isEditable">
            </Input>
        </FormItem>
        <FormItem label="优先级:" prop="priority">
            <Input v-model="groupForm.priority" placeholder="" :disabled="deleteFlag==='1'|| !isEditable">
            </Input>
        </FormItem>
    </Form>
     <br>
      <Collapse value="1">
          <Panel name="1">
              规则信息
              <p slot="content">
                <Table :columns="ruleColumns" :data="ruleData"></Table>
                <Button type="primary" icon="md-add" @click="addEmptyRow"  style="margin-top:5px;" v-if="deleteFlag==='0'&& isEditable"></Button>
              </p>
          </Panel>
      </Collapse>
       <br>
      <Collapse value="1">
          <Panel name="1">
              处理人节点信息
              <p slot="content">
                <Table :columns="userNodeColumns" :data="userCodeData"></Table>
                <Button type="primary" icon="md-add" @click="addUserNodeEmptyRow" style="margin-top:5px;" v-if="deleteFlag==='0'&& isEditable"></Button>
              </p>
          </Panel>
      </Collapse>
      <br>
       <Row>
          <div align="center">
              <Button type="primary" @click="submitForm" v-if="deleteFlag==='0'&& isEditable">保存</Button>
          </div>
      </Row>
  </Card>
</template>
<script>

export default {
  data () {
    const validateRepeat = (rule, value, callback) => {
      if (value && value != null && value !== '') {
        var param = {
          groupName: value
        }
        if (this.groupId && this.tempGroupData.groupName === this.groupForm.groupName) callback()
        this.$ajax.post(this.baseUrl + 'approve/workgroup/service/checkGroupIsExist', param).then(re => {
          var data = re.data
          var code = data.code
          if (code === 'success' && data.data > 0) {
            callback(new Error('工作组名称已经存在'))
          } else {
            callback()
          }
        }).catch(er => {
          callback()
        })
      } else {
        callback()
      }
    }
    return {
      baseUrl: this.$appContext.marvels_core_approve,
      groupId: this.$route.params.id,
      deleteFlag: this.$route.params.deleteFlag,
      isEditable: this.$route.params.isEditable,
      tempGroupData: null,
      groupForm: {
        groupName: null,
        priority: null,
        groupCode: null
      },
      ruleData: [],
      userCodeData: [],
      tempRuleData: [], // 规则临时数据
      tempUerCodeData: [],
      ruleEmptyRowData: { // 规则表格空行对象
        id: null,
        ruleType: null,
        ruleTypeName: null,
        content: null,
        priority: null,
        floorValue: null,
        upperValue: null
      },
      userCodeEmptyRowData: {// 用户节点表格空对象
        id: null,
        userCode: null,
        nodeCode: null,
        userName: null,
        nodeName: null
      },
      ruleTypeList: [{
        value: '1',
        label: '金额'
      }, {
        value: '2',
        label: '产品'
      }],
      productTypeList: [], // 产品下拉列表
      userList: [], // 用户列表
      nodeList: [], // 节点列表
      ruleColumns: [
        {
          type: 'index',
          title: '序号',
          width: 60
        },
        {
          title: '类型',
          key: 'ruleType',
          width: 300,
          render: (h, params) => {
            var vm = this
            return h('div', [
              h(
                'Select',
                {
                  props: {
                    value: params.row.ruleType,
                    disabled: vm.deleteFlag === '1' || !vm.isEditable,
                    'label-in-value': true
                  },
                  on: {
                    'on-change' (e) {
                      if (vm.tempRuleData[params.index]) {
                        vm.tempRuleData[params.index].floorValue = null
                      }
                      if (vm.tempRuleData[params.index]) {
                        vm.tempRuleData[params.index].upperValue = null
                      }

                      vm.initRuleDataObject(params)
                      vm.$set(vm.tempRuleData[params.index], 'ruleType', e.value)
                      vm.$set(vm.tempRuleData[params.index], 'ruleTypeName', e.label)
                      vm.ruleData = vm.cloneObject(vm.tempRuleData)
                    }
                  }
                },
                vm.ruleTypeList.map(function (type) {
                  return h(
                    'Option',
                    {
                      props: { value: type.value }
                    },
                    type.label
                  )
                })
              )
            ])
          }
        },
        {
          title: '规则',
          key: 'content',
          width: 400,
          render: (h, params) => {
            var vm = this
            if (params.row.ruleType === '1') {
              return h('div', [
                h(
                  'InputNumber',
                  {
                    style: {
                      'width': '100px',
                      'float': 'left'
                    },
                    props: {
                      value: params.row.floorValue,
                      disabled: vm.deleteFlag === '1' || !vm.isEditable
                    },
                    on: {
                      'on-change': e => {
                        vm.initRuleDataObject(params)
                        vm.$set(vm.tempRuleData[params.index], 'floorValue', e)
                        // vm.ruleData = vm.cloneObject(vm.tempRuleData)
                      }
                    }
                  }
                ),
                h('div', {
                  style: {
                    'width': '20px',
                    'float': 'left'
                  }
                }, '到'),
                h(
                  'InputNumber',
                  {
                    style: {
                      'width': '100px',
                      'float': 'left'
                    },
                    props: {
                      value: params.row.upperValue,
                      disabled: vm.deleteFlag === '1' || !vm.isEditable,
                      min: 0,
                      'empty': true
                    },
                    on: {
                      'on-change': e => {
                        vm.initRuleDataObject(params)
                        vm.$set(vm.tempRuleData[params.index], 'upperValue', e)
                        // vm.ruleData = vm.cloneObject(vm.tempRuleData)
                      }
                    }
                  }
                )
              ])
            }
            if (params.row.ruleType === '2') {
              return h('div', [
                h(
                  'Select',
                  {
                    props: {
                      value: params.row.floorValue,
                      disabled: vm.deleteFlag === '1' || !vm.isEditable,
                      'label-in-value': true
                    },
                    on: {
                      'on-change' (e) {
                        vm.initRuleDataObject(params)
                        vm.$set(vm.tempRuleData[params.index], 'floorValue', e.value)
                        vm.ruleData = vm.cloneObject(vm.tempRuleData)
                      }
                    }
                  },
                  vm.productTypeList.map(function (type) {
                    return h(
                      'Option',
                      {
                        props: { value: type.productType }
                      },
                      type.productTypeName
                    )
                  })
                )
              ])
            }
          }
        },
        {
          title: '优先级',
          key: 'priority',
          render: (h, params) => {
            const vm = this
            return h('InputNumber', {
              props: {
                type: 'text',
                value: params.row.priority,
                disabled: vm.deleteFlag === '1' || !vm.isEditable,
                min: 1
              },
              on: {
                'on-change' (e) {
                  vm.initRuleDataObject(params)
                  vm.$set(vm.tempRuleData[params.index], 'priority', e)
                  // vm.ruleData = vm.cloneObject(vm.tempRuleData)
                }
              }
            })
          }
        },
        {
          title: '操作',
          render: (h, param) => {
            const vm = this
            if (vm.deleteFlag === '0' && vm.isEditable) {
              return h('div', {}, [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '12px'
                  },
                  on: {
                    click: () => {
                      vm.deleteRuleRow(param)
                    }
                  }
                }, '删除')
              ])
            }
          }
        }
      ],
      userNodeColumns: [
        {
          type: 'index',
          title: '序号',
          width: 80
        },
        {
          title: '处理人',
          key: 'userCode',
          render: (h, params) => {
            var vm = this
            return h('div', [
              h(
                'Select',
                {
                  props: {
                    value: params.row.userCode,
                    disabled: vm.deleteFlag === '1' || !vm.isEditable,
                    'label-in-value': true,
                    'filterable': true
                  },
                  on: {
                    'on-change' (e) {
                      vm.inituserNodeDataObject(params)
                      vm.$set(vm.tempUerCodeData[params.index], 'userCode', e.value)
                      vm.$set(vm.tempUerCodeData[params.index], 'userName', e.label)
                      vm.userCodeData = vm.cloneObject(vm.tempUerCodeData)
                    }
                  }
                },
                vm.userList.map(function (type) {
                  return h(
                    'Option',
                    {
                      props: { value: type.value }
                    },
                    type.label
                  )
                })
              )
            ])
          }
        },
        {
          title: '节点',
          key: 'nodeCode',
          render: (h, params) => {
            var vm = this
            return h('div', [
              h(
                'Select',
                {
                  props: {
                    value: params.row.nodeCode,
                    disabled: vm.deleteFlag === '1' || !vm.isEditable,
                    'label-in-value': true
                  },
                  on: {
                    'on-change' (e) {
                      vm.inituserNodeDataObject(params)
                      vm.$set(vm.tempUerCodeData[params.index], 'nodeCode', e.value)
                      vm.$set(vm.tempUerCodeData[params.index], 'nodeName', e.label)
                      vm.userCodeData = vm.cloneObject(vm.tempUerCodeData)
                    }
                  }
                },
                vm.nodeList.map(function (type) {
                  return h(
                    'Option',
                    {
                      props: { value: type.value }
                    },
                    type.label
                  )
                })
              )
            ])
          }
        },
        {
          title: '操作',
          render: (h, param) => {
            const vm = this
            if (vm.deleteFlag === '0' && vm.isEditable) {
              return h('div', {}, [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '12px'
                  },
                  on: {
                    click: () => {
                      vm.deleteUserCodeRow(param)
                    }
                  }
                }, '删除')
              ])
            }
          }
        }
      ],
      validRules: {
        groupName: [
          { required: true, message: '工作组名称不能为空', trigger: 'blur' },
          { validator: validateRepeat, trigger: 'blur' }
        ],
        priority: [
          { required: true, message: '优先级不能为空', trigger: 'blur' },
          { pattern: this.$util.regExpNum, message: '优先级不能为非数字类型', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
  },
  created () {
    this.$ajax = this.$util.ajax()
    this.initSelect()
    this.initPage()
  },
  mounted () {},
  methods: {
    initSelect () {
      // 初始化产品
      this.$ajax.post(this.$appContext.marvels_core_product + '/product/api/mcptProductTypeInfo', {}).then(re => {
        this.productTypeList = re.data
      }).catch(er => {
      })
      // 初始化用户/节点
      this.$ajax.post(this.$appContext.marvels_core_approve + 'approve/workgroup/service/selectDropDownDatas').then(re => {
        var data = re.data.data || []
        data.userList.forEach(item => {
          var sData = {}
          sData.value = item.userCode
          sData.label = item.userNamep
          this.userList.push(sData)
        })
        data.nodeList.forEach(item => {
          var sData = {}
          sData.value = item.nodeCode
          sData.label = item.nodeName
          this.nodeList.push(sData)
        })
      }).catch(er => {
      })
    },
    initPage () {
      var vm = this
      if (vm.groupId) {
        vm.$ajax.post(vm.$appContext.marvels_core_approve + 'approve/workgroup/service/selectWorkGroupInfo', {id: vm.groupId}).then(re => {
          var datas = re.data.data || {}
          vm.groupForm.groupName = datas.groupName
          vm.groupForm.groupCode = datas.groupCode
          vm.groupForm.priority = datas.priority == null ? '' : datas.priority + ''
          vm.ruleData = datas.rules
          vm.ruleData.forEach(item => {
            if (item.ruleType === '1') {
              if (item.floorValue) {
                item.floorValue = Number(item.floorValue)
              }
              if (item.upperValue) {
                item.upperValue = Number(item.upperValue)
              }
            }
          })

          vm.userCodeData = datas.userNodes
          vm.tempRuleData = vm.cloneObject(vm.ruleData)
          vm.tempUerCodeData = vm.cloneObject(vm.userCodeData)
          vm.tempGroupData = vm.cloneObject(datas)
        }).catch(er => {
        })
      }
    },
    // 规则信息列表 动态添加一行
    addEmptyRow () {
      this.ruleData = this.cloneObject(this.tempRuleData)
      // 设置默认值(默然与上一行的规则类型相同)
      var size = this.tempRuleData.length
      if (size > 0) {
        var ruleType = this.tempRuleData[size - 1].ruleType
        this.ruleEmptyRowData.ruleType = ruleType
        this.ruleEmptyRowData.ruleTypeName = this.tempRuleData[size - 1].ruleTypeName
      }
      this.ruleData.push(this.cloneObject(this.ruleEmptyRowData))
      this.tempRuleData.push(this.cloneObject(this.ruleEmptyRowData))
    },
    // 初始化规则数组数据对象
    initRuleDataObject (params) {
      if (!this.tempRuleData[params.index]) {
        this.tempRuleData[params.index] = {
          floorValue: null,
          upperValue: null,
          priority: null
        }
      }
    },
    // 复制对象
    cloneObject (obj) {
      return JSON.parse(JSON.stringify(obj))
    },
    addUserNodeEmptyRow () {
      this.userCodeData = this.cloneObject(this.tempUerCodeData)
      // 设置默认值(默然与上一行的 处理人相同)
      var size = this.tempUerCodeData.length
      if (size > 0) {
        var userCode = this.tempUerCodeData[size - 1].userCode
        this.userCodeEmptyRowData.userCode = userCode
        this.userCodeEmptyRowData.userName = this.tempUerCodeData[size - 1].userName
      }
      this.userCodeData.push(this.cloneObject(this.userCodeEmptyRowData))
      this.tempUerCodeData.push(this.cloneObject(this.userCodeEmptyRowData))
    },
    // 初始化规则数组数据对象
    inituserNodeDataObject (params) {
      if (!this.tempUerCodeData[params.index]) {
        this.tempUerCodeData[params.index] = {}
      }
    },
    // 保存提交
    submitForm () {
      var vm = this
      this.$refs.groupForm.validate(valid => {
        if (valid) {
          vm.ruleData = vm.cloneObject(vm.tempRuleData)
          var rules = []
          var validFlag = true
          if (vm.ruleData && vm.ruleData.length > 0) {
            vm.ruleData.forEach(item => {
              if (!item.ruleType || item.ruleType === '' || item.ruleType == null) {
                vm.$Message.warning('请填写完规则信息')
                validFlag = false
                return
              }
              if ((item.ruleType === 1) && (!item.floorValue || item.floorValue === '' || item.floorValue == null) && (item.upperValue || item.upperValue === '' || item.upperValue == null)) {
                vm.$Message.warning('请填写完规则信息')
                validFlag = false
                return
              }
              if ((item.ruleType === 2) && (!item.floorValue || item.floorValue === '' || item.floorValue == null)) {
                vm.$Message.warning('请填写完规则信息')
                validFlag = false
                return
              }
              if (!item.priority || item.priority === '' || item.priority == null) {
                vm.$Message.warning('请填写完规则信息')
                validFlag = false
                return
              }
              rules.push(item)
            })
          }
          if (!validFlag) return
          var userNodes = []
          if (vm.userCodeData && vm.userCodeData.length > 0) {
            vm.userCodeData.forEach(item => {
              if (!item.userCode || item.userCode === '' || item.userCode == null) {
                vm.$Message.warning('请填写完处理人节点信息')
                validFlag = false
                return
              }
              if (!item.nodeCode || item.nodeCode === '' || item.nodeCode == null) {
                vm.$Message.warning('请填写完处理人节点信息')
                validFlag = false
                return
              }
              userNodes.push(item)
            })
          }
          if (!validFlag) return
          if (vm.groupId) {
            // 更新
            vm.updateDatas(rules, userNodes)
            return
          }
          var param = {
            groupName: vm.groupForm.groupName,
            rules: rules,
            priority: vm.groupForm.priority,
            userNodes: userNodes
          }
          vm.$ajax.post(vm.baseUrl + 'approve/workgroup/service/saveGroupWorkInfo', param).then(re => {
            var data = re.data
            var code = data.code
            var message = data.message
            if (code !== 'success') {
              vm.$Message.warning(message)
              return
            }
            if (code === 'success') {
              if (data.data && data.data !== '' && data.data != null && data.data.length > 0) {
                sessionStorage['nodeGroupList'] = data.data ? JSON.stringify(data.data) : ''
              }
              vm.$Message.success('保存成功')
              this.$router.push({ name: 'workgroup' })
            }
          }).catch(er => {

          })
        }
      })
    },
    // 更新
    updateDatas (rules, userNodes) {
      var vm = this
      var param = {
        id: vm.groupId,
        priority: vm.groupForm.priority,
        rules: rules,
        userNodes: userNodes,
        groupName: vm.groupForm.groupName,
        groupCode: vm.groupForm.groupCode
      }
      vm.$ajax.post(vm.baseUrl + 'approve/workgroup/service/updateGroupDatas', param).then(re => {
        var data = re.data
        var code = data.code
        var message = data.message
        if (code !== 'success') {
          vm.$Message.warning(message)
          return
        }
        if (code === 'success') {
          if (data.data && data.data !== '' && data.data != null && data.data.length > 0) {
            sessionStorage['nodeGroupList'] = data.data ? JSON.stringify(data.data) : ''
          }
          vm.$Message.success('保存成功')
          this.$router.push({ name: 'workgroup' })
        }
      }).catch(er => {

      })
    },
    // 删除用户节点信息
    deleteUserCodeRow (params) {
      var vm = this
      var config = {
        title: '提示',
        content: '是否确认删除?',
        onOk: function () {
          var row = params.row
          if (!row.id) { // 新增但是还未保存的房产记录
            vm.tempUerCodeData.splice(params.index, 1)
            vm.userCodeData = vm.cloneObject(vm.tempUerCodeData)
            return
          }
          row.deleteFlag = '1'
          var param = {
            id: vm.groupId,
            userNodes: [row]
          }
          vm.$ajax.post(vm.baseUrl + 'approve/workgroup/service/updateGroupDatas', param).then(re => {
            var data = re.data
            var code = data.code
            var message = data.message
            if (code !== 'success') {
              vm.$Message.warning(message)
              return
            }
            vm.tempUerCodeData.splice(params.index, 1)
            vm.userCodeData = vm.cloneObject(vm.tempUerCodeData)
          }).catch(er => {

          })
        }
      }
      this.$Modal.confirm(config)
    },
    // 删除规则信息
    deleteRuleRow (params) {
      var vm = this
      var config = {
        title: '提示',
        content: '是否确认删除?',
        onOk: function () {
          var row = params.row
          if (!row.id) { // 新增但是还未保存的房产记录
            vm.tempRuleData.splice(params.index, 1)
            vm.ruleData = vm.cloneObject(vm.tempRuleData)
            return
          }
          row.deleteFlag = '1'
          var param = {
            id: vm.groupId,
            rules: [row]
          }
          vm.$ajax.post(vm.baseUrl + 'approve/workgroup/service/updateGroupDatas', param).then(re => {
            var data = re.data
            var code = data.code
            var message = data.message
            if (code !== 'success') {
              vm.$Message.warning(message)
              return
            }
            vm.tempRuleData.splice(params.index, 1)
            vm.ruleData = vm.cloneObject(vm.tempRuleData)
          }).catch(er => {

          })
        }
      }
      this.$Modal.confirm(config)
    }
  }
}
</script>

<style lang="less">
</style>
